package com.hmdp.service.impl;

import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryTypeList() {
        //查询缓存
        List<String> shopTypeJsonList = redisTemplate.opsForList().range("shopTypeList", 0, -1);
        if(Objects.nonNull(shopTypeJsonList) && !shopTypeJsonList.isEmpty()){
            //缓存命中 json-->bean
            List<ShopType> shopTypeList = shopTypeJsonList.stream().map((shopTypeJson) -> JSONUtil.toBean(shopTypeJson, ShopType.class)).collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }
        //缓存未命中，查数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if(Objects.isNull(shopTypeList) || shopTypeList.isEmpty()){
            //数据库不存在
            return Result.fail("店铺类型数据不存在");
        }
        //存缓存
        shopTypeJsonList = shopTypeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        redisTemplate.opsForList().rightPushAll("shopTypeList",shopTypeJsonList);

        return Result.ok(shopTypeList);
    }
}
